/*
 * gx_globals.c
 *
 *  Created on: 2012-3-15
 *      Author: zhangguanxing
 *      Description:
 */


#include "gx.h"
#include "unistd.h"

static int
init_log(gx_globals_t* g){
	g->g_log = (gx_log_t*)gx_malloc(sizeof(gx_log_t));
	int ret;
	#ifdef GX_LOG_PATH
		ret = gx_set_log_file(GX_LOG_PATH);
		if(ret != 0)
			return ret;
	#else
		g->g_log->filefd = STDOUT_FILENO;
		g->g_log->log_path = "";
	#endif

	#ifdef GX_ENABLE_ANSI_COLOR
		g->g_log->enable_color_log = 1;
	#else
		g->g_log->enable_color_log = 0;
	#endif
	#ifndef GX_LOG_LEVEL
		gx_set_log_level(GX_LOG_TRACE);
	#else
		gx_set_log_level(GX_LOG_LEVEL);
	#endif

	pthread_mutex_init(&(g->g_log->mutex), NULL);

	return 0;
}
static int
init_hash_algorithm(gx_globals_t* g){
	g->g_hash = (gx_hash_t*)gx_malloc(sizeof(gx_hash_t));
	#ifdef GX_HASH_ALGORITHM_TIME33
		g->g_hash->hash = time33;
		gx_set_string(g->g_hash->algorithm_descritpion, "time33");
		return 0;
	#endif
	return -1;
}
static int
init_hashring(gx_globals_t* g){
	g->g_hashring = (gx_hashring_t*)gx_malloc(sizeof(gx_hashring_t));
	#ifdef GX_USE_LOAD_BALANCE
		#include "gx_hashring_vnodeimpl.h"
		g->g_hashring->add_node = gx_vnode_add_node;
		g->g_hashring->delete_node = gx_vnode_delete_node;
		g->g_hashring->select_node_for_key = gx_vnode_delete_node;
		g->g_hashring->init_ring =gx_vnode_init_ring;
	#else
		#include "gx_hashring_purenodeimpl.h"
		g->g_hashring->copy_to_ring= gx_pure_copy_to_ring;
		g->g_hashring->add_node = gx_pure_add_node;
		g->g_hashring->delete_node = gx_pure_delete_node;
		g->g_hashring->select_node_for_key = gx_pure_select_node;
		g->g_hashring->init_ring =gx_pure_init_ring;
	#endif
	int result = g->g_hashring->init_ring(g->g_hashring);
	if(result != 0){
		GX_ERROR_LOG("init hashring error");
		return result;
	}
	return 0;
}

int
init_globals(gx_globals_t* g) {
	assert(g != NULL);
	memset(g, 0, sizeof(gx_globals_t));

	if(init_log(g) != 0)
		goto error;

	if(init_hash_algorithm(g) != 0)
		goto error;

	if(init_hashring(g) != 0)
		goto error;

	g->is_inited = 1;

	return 0;
error:
	g->is_inited = 0;
	return -1;
}

